package com.ruoyi.demo.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.common.excel.ExcelListener;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.ValidatorUtils;
import com.ruoyi.common.utils.spring.SpringUtils;

import com.ruoyi.demo.domain.vo.HtWorkloadVo;
import com.ruoyi.demo.domain.vo.HtWorkloadImportVo;
import com.ruoyi.demo.domain.bo.HtWorkloadBo;
import com.ruoyi.demo.service.IHtWorkloadService;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static com.ruoyi.common.core.mapper.BaseMapperPlus.log;
import static com.ruoyi.demo.constant.HTCommon.HT_PREFIX;

public class HtWorkloadImportListener extends AnalysisEventListener<HtWorkloadImportVo> implements ExcelListener<HtWorkloadImportVo> {
    private final IHtWorkloadService iHtWorkloadService;
    private final Boolean isUpdateSupport;
    private final String operName;
    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public HtWorkloadImportListener(Boolean isUpdateSupport) {
        this.iHtWorkloadService = SpringUtils.getBean(IHtWorkloadService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<HtWorkloadImportVo> getExcelResult() {
        return new ExcelResult<HtWorkloadImportVo>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<HtWorkloadImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }

        };
    }

    @Override
    public void invoke(HtWorkloadImportVo importVo, AnalysisContext analysisContext) {
        HtWorkloadVo vo = this.iHtWorkloadService.queryById(importVo.getId());
        String baseNumber = StrUtil.subBefore(importVo.getPartNumber(), "-", true);
        try {
            // 验证是否存在这个信息单号
            if (ObjectUtil.isNull(vo)) {
                HtWorkloadBo bo = BeanUtil.toBean(importVo, HtWorkloadBo.class);
                ValidatorUtils.validate(bo);
                bo.setBaseNumber(baseNumber);
                String firstSix = bo.getRoute().substring(0, 6);
                if (firstSix.equals(HT_PREFIX)) {
                    bo.setFlag("1");
                }
                if (bo.getPlanDate() == null){
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(bo.getReleaseDate());
                    calendar.add(Calendar.DAY_OF_YEAR, 5);
                    Date newPlanDate = calendar.getTime();
                    bo.setPlanDate(newPlanDate);
                    bo.setCraftsDate(newPlanDate);
                    bo.setProofDate(newPlanDate);
                }
                bo.setCreateBy(operName);
                iHtWorkloadService.insertByBo(bo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、项目 ").append(importVo.getPartNumber()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long id = vo.getId();
                HtWorkloadBo bo = BeanUtil.toBean(importVo, HtWorkloadBo.class);
                bo.setId(id);
                ValidatorUtils.validate(bo);
                bo.setUpdateBy(operName);
                iHtWorkloadService.updateByBo(bo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、项目 ").append(importVo.getPartNumber()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、项目 ").append(importVo.getPartNumber()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、热处理工艺报 " + importVo.getId() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }
}
